package model

// by daoyi
import "simai_oa/tool"

type Admin struct {
	Id   int    `json:"id" form:"id" gorm:"type:int(11) unsigned"`
	Name string `json:"name" form:"name" gorm:"type:varchar(50)" binding:"required"`
	// Pwd           string `json:"pwd" form:"pwd" gorm:"varchar(64)" binding:"required,eqfield=Password"`
	Pwd           string  `json:"pwd" form:"pwd" gorm:"type:varchar(64)" binding:"required"`
	Salt          string  `json:"salt" form:"salt" gorm:"type:varchar(64)"`
	OpenId        string  `json:"-" form:"open_id" gorm:"type:varchar(128);comment:微信open_id"`
	GameId        int     `json:"game_id" form:"game_id" gorm:"type:int(5);comment:管理员类型 1业务员 2财务员 3采购员 4仓库员 5曹总 6技术员"`
	RealName      string  `json:"real_name" form:"real_name" gorm:"type:varchar(20)"`
	Tel           string  `json:"tel" form:"tel" gorm:"type:varchar(20)"`
	Switch        int     `json:"switch" form:"switch" gorm:"type:int(4);comment:1正常，2禁用"`
	Operator      string  `json:"operator" form:"operator" gorm:"type:varchar(20)"`
	LastLoginIp   string  `json:"last_login_ip" form:"last_login_ip" gorm:"type:varchar(64)"`
	LastLoginTime int     `json:"last_login_time" form:"last_login_time" gorm:"type:int(11)"`
	LoginLimit    int     `json:"login_limit" form:"login_limit" gorm:"type:int(4)"`
	Type          int     `json:"type" form:"type" gorm:"default:2;type:int(4);comment:1部门管理员，2普通员工"`
	RoleId        int     `json:"role_id" form:"role_id"`
	RoleName      string  `json:"role_name" form:"role_name"`
	Order         []Order `gorm:"foreignKey:duty" json:"order"`
}

// 删除用户及关联数据
func (Admin) Delete(adminsids []int) error {
	tx := tool.Gdb.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Where("id in (?)", adminsids).Delete(&Admin{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Where("admins_id in (?)", adminsids).Delete(&Admin{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}

// 分配用户角色
func (Admin) SetAdminRole(adminsid int, roleids []int) error {
	tx := tool.Gdb.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Where(&Admin{Id: adminsid}).Delete(&Admin{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	if len(roleids) > 0 {
		for _, rid := range roleids {
			rm := new(Admin)
			rm.RoleId = rid
			rm.Id = adminsid
			if err := tx.Create(rm).Error; err != nil {
				tx.Rollback()
				return err
			}
		}
	}
	return tx.Commit().Error
}
